package com.hongdee.base.carmodel.service.impl;

import com.hongdee.base.Common;
import com.hongdee.base.car.entity.TBcCar;
import com.hongdee.base.carconfigure.service.ICarConfigureService;
import com.hongdee.base.carmodel.dao.ICarModelDao;
import com.hongdee.base.carmodel.entity.TBcCarModel;
import com.hongdee.base.carmodel.service.ICarModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 名  称:CarMoldeServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.base.carmodel.service.impl
 * 作  者: 术洪超
 * 日  期:2017-05-18 10:49
 */
@Service
public class CarMoldeServiceImpl implements ICarModelService {

    String tabName = "T_BC_CARMODEL";
    String entityName = "TBcCarModel";

    @Autowired
    private ICarModelDao iCarModelDao;

    @Autowired
    private ICarConfigureService iCarConfigureService;
    //查询车型

    private List CarModel(String carSeriesId,String bCode) throws Exception {
        return this.iCarModelDao.list("select * from t_bc_carmodel where series_id = ? and brand_code = ? ", carSeriesId,bCode);
    }

    private Map queryBrand(String seriesId) throws Exception {
        List params = new ArrayList();
        String sql = "select brand_code from t_bc_car_series where id = ? limit 1";
        params.add(seriesId);

        return this.iCarModelDao.info(sql, params.toArray());

    }


    /**
     * @param carSeriesId 车系ID
     * @return List<Map>
     * @throws Exception
     * @desc 构建车型树
     * @author 术洪超
     */
    @Override
    public List<Map> buildTreeNodeList(String carSeriesId, String  bCode,int showLevel) throws Exception {

        List<Map> allModels = CarModel(carSeriesId,bCode);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allModels) {
            Map mapModel = new HashMap();
            mapModel.put("label", tempS.get("modelName"));
            mapModel.put("value", tempS.get("id"));
            mapModel.put("code",tempS.get("modelCode"));
            //车型
            mapModel.put("type", "2");
            if (showLevel > 2) {
                mapModel.put("child", iCarConfigureService.buildTreeNodeList(tempS.get("id").toString(),bCode));
            }
            all.add(mapModel);
        }
        return all;
    }

    /**
     * 加厂牌号的树
     * @param carSeriesId 车系ID
     * @return List<Map>
     * @throws Exception
     * @desc 构建车型树
     */
    @Override
    public List<Map> buildTreeNodeLists(String carSeriesId, String  bCode,int showLevel) throws Exception {

        List<Map> allModels = CarModels(carSeriesId,bCode);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allModels) {
            Map mapModel = new HashMap();
            mapModel.put("label", tempS.get("modelName"));
            mapModel.put("value", tempS.get("id"));
            mapModel.put("code",tempS.get("modelCode"));
            mapModel.put("number",tempS.get("labelNumber"));
            //车型
            mapModel.put("type", "2");
            if (showLevel > 2) {
                mapModel.put("child", iCarConfigureService.buildTreeNodeList(tempS.get("id").toString(),bCode));
            }
            all.add(mapModel);
        }
        return all;
    }

    /**
     * 加厂牌号的查询
     * @param carSeriesId
     * @param bCode
     * @return
     * @throws Exception
     */
    private List CarModels(String carSeriesId,String bCode) throws Exception {
        return this.iCarModelDao.list("select c.*,s.label_number from t_bc_carmodel c,t_bc_car_series s where c.series_id = s.id and c.series_id = ? and c.brand_code = ? ", carSeriesId,bCode);
    }
/*
    *
     * @param carSeriesId 车系ID
     * @return List<Map>
     * @throws Exception
     * @desc 构建车型树
     * @author 术洪超
*/
   /* @Override
    public List<Map> buildTreeNodeList(String carSeriesId, String  bCode,int showLevel) throws Exception {

        List<Map> allModels = CarModel(carSeriesId,bCode);
        List<Map> all = new ArrayList<>();

        for (Map tempS : allModels) {
            Map mapModel = new HashMap();
            mapModel.put("label", tempS.get("modelName"));
            mapModel.put("value", tempS.get("id"));
            mapModel.put("code",tempS.get("modelCode"));
            //车型
            mapModel.put("type", "2");
            if (showLevel > 2) {
                mapModel.put("child", iCarConfigureService.buildTreeNodeList(tempS.get("id").toString(),bCode));
            }
            all.add(mapModel);
        }
        return all;
    }*/


    /**
     * @param data 要保存的实体
     * @return Map
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @Override
    public TBcCarModel saveOrUpdate(TBcCarModel data, String uid) throws Exception {

        if (data.getModelCode() == null||data.getModelCode().equals("")) {
            throw new Exception("车型编码不能为空！");
        }
        if (data.getModelName() == null||data.getModelName().equals("")) {
            throw new Exception("车型名称不能为空！");
        }
        if(data.getVinCode()==null||data.getVinCode().equals("")){
            throw new Exception("vin识配码不能为空！");
        }
        if (data.getId() == null) {

            if (existModelCode(data.getModelCode())) {
                throw new Exception("车型编码已存在！");
            }
            if (existModelName(data.getModelName())) {
                throw new Exception("车型名称已存在！");
            }
            if (existModelVinCode(data.getVinCode())){
                throw new Exception("vin识配码已存在！");
            }

            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());
            data.setResStatus("1");

            Map map = this.queryBrand(data.getSeriesId());
            data.setBrandCode(map.get("brandCode").toString());

        } else {
         Map map = this.iCarModelDao.info("select * from T_BC_CARMODEL where id=?",data.getId());
         if(!data.getModelCode().equals(map.get("modelCode"))){
             if (existModelCode(data.getModelCode())) {
                 throw new Exception("车型编码已存在！");
             }
         }
         if(!data.getModelName().equals(map.get("modelName"))){
             if (existModelName(data.getModelName())) {
                 throw new Exception("车型名称已存在！");
             }
         }
         if(!data.getVinCode().equals(map.get("vinCode"))){
             if (existModelVinCode(data.getVinCode())){
                 throw new Exception("vin识配码已存在！");
             }
         }
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }
        this.iCarModelDao.saveOrUpdate(data);
        return data;
    }


    /**
     * @param id     主键 ID
     * @param status 状态
     * @return
     * @throws Exception
     * @desc 修改状态
     * @author 术洪超
     */
    @Override
    public void update(String id, String status) throws Exception {

        Map map = new HashMap();
        String hql = "update " + entityName + " set resStatus =:status where id =:id";
        map.put("status", status);
        map.put("id", id);
        this.iCarModelDao.update(hql, map);

    }


    /**
     * @param id 主键
     * @return Map
     * @throws Exception
     * @desc 车型详细
     * @author 术洪超
     */
    @Override
    public Map info(String id) throws Exception {
        if (StringUtils.isEmpty(id)) {
            throw new Exception("请选择车型！");
        }
        List params = new ArrayList();
        String sql = "select * from " + tabName + " where id = ? ";
        params.add(id);
        return this.iCarModelDao.info(sql, params.toArray());
    }

    /**
     * @param start    起始记录
     * @param limit    页面大小
     * @param seriesId 车系ID
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
     @Override
     public Map page(String start, String limit, String seriesId, String modelCode) throws Exception {

        StringBuffer sql = new StringBuffer();
        sql.append("select * from " + tabName);

        List params = new ArrayList();

        Common common = new Common();
        Boolean hasWhere = false;

        if (!StringUtils.isEmpty(modelCode)) {

            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" model_code like ? ");
            params.add("%" + modelCode + "%");
        }

        if (!StringUtils.isEmpty(seriesId)) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" series_id = ? ");
            params.add(seriesId);
        }
        return this.iCarModelDao.page(sql.toString(), params.toArray(), start, limit);

    }

    //判断车型编码是否存在

    private boolean existModelCode(String modelCode) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName);

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!modelCode.isEmpty() && !modelCode.equals("")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" model_code = ? ");
            params.add(modelCode);
        }

        Map map = this.iCarModelDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

    //判断车型编码是否存在
    private boolean existModelName(String modelName) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName);

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!modelName.isEmpty() && !modelName.equals("modelName")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" model_name = ? ");
            params.add(modelName);
        }

        Map map = this.iCarModelDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }


    /**
     * 车型下拉
     * @param seriesId
     * @return
     * @throws Exception
     */
    @Override
    public List<Map> combo(String seriesId) throws Exception {
        List params = new ArrayList();
        String sql = " select * from " + tabName + " where series_id = ? and res_status = '1' order by create_time desc";
        params.add(seriesId);
        List<Map<String, Object>> mapList = this.iCarModelDao.list(sql, params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        for (Map map : mapList) {
            temp = new HashMap();
            temp.put("value", map.get("id"));
            temp.put("code",map.get("modelName"));
            temp.put("label", map.get("modelName"));
            resList.add(temp);
        }
        return resList;
    }

    @Override
    public TBcCarModel getInfo(String id) throws Exception {
        return this.iCarModelDao.info(id);
    }

    @Override
    public TBcCarModel getInfoByCode(String code) throws Exception {
        return null;
    }

    //判断车型识配码是否存在
    private boolean existModelVinCode(String vinCode) throws Exception {

        StringBuffer sb = new StringBuffer();
        sb.append("select * from " + tabName);

        List params = new ArrayList();
        Common common = new Common();
        Boolean hasWhere = false;
        if (!vinCode.isEmpty() && !vinCode.equals("vinCode")) {
            hasWhere = common.appendWhereIfNeed(sb, hasWhere);
            sb.append(" vin_code = ? ");
            params.add(vinCode);
        }

        Map map = this.iCarModelDao.page(sb.toString(), params.toArray(), null, null);
        return Integer.valueOf(map.get("total").toString()) > 0;

    }

}
